import { io, Socket } from 'socket.io-client';
import { getVisitorUuid } from '../utils/userUtils';

// WebSocket连接状态枚举
export enum ConnectionState {
  DISCONNECTED = 'disconnected',
  CONNECTING = 'connecting',
  CONNECTED = 'connected',
  AUTHENTICATED = 'authenticated',
  RECONNECTING = 'reconnecting',
  ERROR = 'error'
}

// 事件监听器类型
type EventListener = (...args: any[]) => void;

/**
 * WebSocket服务类 - 负责处理与WebSocket服务器的实时通信
 */
class WebSocketService {
  private socket: Socket | null = null;
  private connectionState: ConnectionState = ConnectionState.DISCONNECTED;
  private listeners: Map<string, Set<EventListener>> = new Map();
  // 从环境变量中获取WebSocket URL，如果不存在则使用默认值
  private url: string = import.meta.env.VITE_NODE_API_BASE_URL || 'http://127.0.0.1:3000';
  private reconnectAttempts: number = 0;
  private maxReconnectAttempts: number = 5;
  private reconnectionDelay: number = 1000;
  private connectionTimeout: number = 20000;

  /**
   * 初始化WebSocket连接
   * @param url WebSocket服务器URL，默认从环境变量获取
   */
  connect(url: string = this.url): void {
    if (this.socket && this.socket.connected) {
      return;
    }

    // 更新URL
    if (url) {
      this.url = url;
    }

    this.updateConnectionState(ConnectionState.CONNECTING);

    try {
      // 创建Socket.io连接
      this.socket = io(this.url, {
        reconnectionAttempts: this.maxReconnectAttempts,
        reconnectionDelay: this.reconnectionDelay,
        timeout: this.connectionTimeout
      });

      // 设置事件监听器
      this.setupEventListeners();
    } catch (error) {
      this.updateConnectionState(ConnectionState.ERROR);
    }
  }

  /**
   * 设置Socket.io事件监听器
   */
  private setupEventListeners(): void {
    if (!this.socket) return;

    // 先移除所有现有的监听器，避免重复
    this.socket.removeAllListeners();

    // 连接成功事件
    this.socket.on('connect', () => {
      this.reconnectAttempts = 0;
      this.updateConnectionState(ConnectionState.CONNECTED);
      this.notifyListeners('connect');

      // 自动进行认证
      this.authenticateWithCurrentUser();
    });

    // 断开连接事件
    this.socket.on('disconnect', (reason) => {
      this.updateConnectionState(ConnectionState.DISCONNECTED);
      this.notifyListeners('disconnect', reason);
    });

    // 连接错误事件
    this.socket.on('connect_error', (error) => {
      this.updateConnectionState(ConnectionState.ERROR);
      this.notifyListeners('error', error);

      // 处理重连
      this.reconnectAttempts++;
      if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      }
    });

    // 聊天历史更新事件
    this.socket.on('chat-history-update', (data) => {
      // console.log('📨 收到聊天历史更新:', data);
      // console.log('📨 数据详情:', JSON.stringify(data, null, 2));
      
      // 触发自定义事件用于全局调试
      const event = new CustomEvent('chat-history-update', { detail: data });
      window.dispatchEvent(event);
      
      this.notifyListeners('chat-history-update', data);
    });

    // 聊天历史列表更新事件 - 新增
    this.socket.on('chat-history-list-update', (data) => {
      // console.log('📋 收到聊天历史列表更新:', data);
      // console.log('📋 数据详情:', JSON.stringify(data, null, 2));
      
      // 检查聊天项中是否有需要显示红点的消息（兼容多种数据格式）
      let chatItems: any[] = [];
      if (Array.isArray(data)) {
        chatItems = data;
      } else if (data && data.data && Array.isArray(data.data)) {
        chatItems = data.data;
      }
      
      const hasUnread = chatItems.some((item: any) => item.lastMessageStatus === 1);
      
      if (hasUnread) {
        // 输出具体的未读消息
        const unreadItems = chatItems.filter((item: any) => item.lastMessageStatus === 1);
      }
      
      // 触发自定义事件用于全局调试
      const event = new CustomEvent('chat-history-list-update', { detail: data });
      window.dispatchEvent(event);
      
      this.notifyListeners('chat-history-list-update', data);
    });

    // 认证响应事件
    this.socket.on('authenticated', (response) => {
      if (response.success) {
        this.updateConnectionState(ConnectionState.AUTHENTICATED);
        this.notifyListeners('authenticated', response);

        // 认证成功后自动订阅聊天历史
        const uuid = getVisitorUuid();
        if (uuid) {
          this.subscribeChatHistory(uuid);
        }
      } else {
        this.notifyListeners('authentication-failed', response);
      }
    });

    // 订阅响应事件
    this.socket.on('subscribed-chat-history', (response) => {
      this.notifyListeners('subscribed-chat-history', response);
    });
  }

  /**
   * 使用当前用户UUID自动认证
   */
  private authenticateWithCurrentUser(): void {
    const uuid = getVisitorUuid();
    if (uuid) {
      this.authenticate(uuid);
    } else {
      console.warn('⚠️ 未找到用户UUID，无法进行WebSocket认证');
    }
  }

  /**
   * 向WebSocket服务器进行认证
   * @param uuid 用户UUID
   */
  authenticate(uuid: string): void {
    if (!this.socket || !this.socket.connected) {
      return;
    }

    this.socket.emit('authenticate', { uuid });
  }

  /**
   * 订阅聊天历史更新
   * @param uuid 用户UUID
   */
  subscribeChatHistory(uuid: string): void {
    if (!this.socket || !this.socket.connected) {
      return;
    }

    this.socket.emit('subscribe-chat-history', { uuid });
  }

  /**
   * 添加事件监听器
   * @param event 事件名称
   * @param callback 回调函数
   */
  addEventListener(event: string, callback: EventListener): void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }
    this.listeners.get(event)?.add(callback);
  }

  /**
   * 移除事件监听器
   * @param event 事件名称
   * @param callback 要移除的回调函数
   */
  removeEventListener(event: string, callback: EventListener): void {
    if (this.listeners.has(event)) {
      this.listeners.get(event)?.delete(callback);
    }
  }

  /**
   * 通知特定事件的所有监听器
   * @param event 事件名称
   * @param args 传递给监听器的参数
   */
  private notifyListeners(event: string, ...args: any[]): void {
    if (this.listeners.has(event)) {
      this.listeners.get(event)?.forEach(callback => {
        try {
          callback(...args);
        } catch (error) {
          // console.error(`事件 ${event} 的监听器执行出错:`, error);
          console.error('event listener execution error', error);
        }
      });
    }
  }

  /**
   * 更新连接状态并通知监听器
   * @param state 新的连接状态
   */
  private updateConnectionState(state: ConnectionState): void {
    this.connectionState = state;
    this.notifyListeners('connection-state-change', state);
  }

  /**
   * 获取当前连接状态
   */
  getConnectionState(): ConnectionState {
    return this.connectionState;
  }

  /**
   * 检查WebSocket是否已连接
   */
  isConnected(): boolean {
    return this.socket?.connected || false;
  }

  /**
   * 断开WebSocket连接
   */
  disconnect(): void {
    if (this.socket) {
      this.socket.disconnect();
      this.socket = null;
      this.updateConnectionState(ConnectionState.DISCONNECTED);
    }
  }
}

// 创建单例实例
export const websocketService = new WebSocketService();
export default websocketService;